<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BMC实验管理平台 - 监控面板</title>
    <!-- Element Plus CSS -->
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <!-- Vue 3 -->
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <!-- Element Plus -->
    <script src="https://unpkg.com/element-plus"></script>
    <!-- Axios -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <!-- ECharts -->
    <script src="https://unpkg.com/echarts@5.4.3/dist/echarts.min.js"></script>
    <style>
        body {
            margin: 0;
            font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif;
            background-color: #f5f7fa;
        }
        #app {
            min-height: 100vh;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px 20px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        }
        .header h1 {
            margin: 0;
            font-size: 28px;
            font-weight: 500;
        }
        .header p {
            margin: 5px 0 0 0;
            opacity: 0.9;
            font-size: 14px;
        }
        .nav-menu {
            background-color: white;
            padding: 0 20px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }
        .main-container {
            padding: 20px;
            max-width: 1600px;
            margin: 0 auto;
        }
        .stats-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }
        .stat-card {
            background: white;
            padding: 24px;
            border-radius: 12px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
            transition: transform 0.3s, box-shadow 0.3s;
        }
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        }
        .stat-card-icon {
            font-size: 40px;
            margin-bottom: 10px;
        }
        .stat-card-value {
            font-size: 32px;
            font-weight: bold;
            margin: 10px 0;
        }
        .stat-card-label {
            font-size: 14px;
            color: #909399;
        }
        .chart-card {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
            margin-bottom: 20px;
        }
        .chart-title {
            font-size: 18px;
            font-weight: 500;
            margin-bottom: 15px;
            color: #303133;
        }
        .chart-container {
            width: 100%;
            height: 400px;
        }
        .instance-list-card {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
        }
        .refresh-btn {
            position: fixed;
            bottom: 40px;
            right: 40px;
            width: 60px;
            height: 60px;
            border-radius: 50%;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
        .status-running {
            color: #409EFF;
        }
        .status-completed {
            color: #67C23A;
        }
        .status-failed {
            color: #F56C6C;
        }
        .status-waiting {
            color: #E6A23C;
        }
    </style>
</head>
<body>
    <div id="app">
        <!-- 页面头部 -->
        <div class="header">
            <h1>BMC实验管理平台</h1>
            <p>监控面板 - 实时监控工作流执行状态</p>
        </div>

        <!-- 导航菜单 -->
        <div class="nav-menu">
            <el-menu mode="horizontal" :default-active="activeMenu" @select="handleMenuSelect">
                <el-menu-item index="templates">实验模板</el-menu-item>
                <el-menu-item index="workflows">工作流</el-menu-item>
                <el-menu-item index="workflow-templates">工作流模板</el-menu-item>
                <el-menu-item index="monitoring">监控面板</el-menu-item>
            </el-menu>
        </div>

        <!-- 主内容区域 -->
        <div class="main-container">
            <!-- 统计卡片 -->
            <div class="stats-cards">
                <div class="stat-card" style="border-left: 4px solid #409EFF;">
                    <div class="stat-card-icon">⏳</div>
                    <div class="stat-card-value status-running">{{ statistics.running_workflows }}</div>
                    <div class="stat-card-label">正在运行</div>
                </div>

                <div class="stat-card" style="border-left: 4px solid #67C23A;">
                    <div class="stat-card-icon">✅</div>
                    <div class="stat-card-value status-completed">{{ statistics.today_success }}</div>
                    <div class="stat-card-label">今日成功</div>
                </div>

                <div class="stat-card" style="border-left: 4px solid #F56C6C;">
                    <div class="stat-card-icon">❌</div>
                    <div class="stat-card-value status-failed">{{ statistics.today_failed }}</div>
                    <div class="stat-card-label">今日失败</div>
                </div>

                <div class="stat-card" style="border-left: 4px solid #E6A23C;">
                    <div class="stat-card-icon">📊</div>
                    <div class="stat-card-value">{{ (statistics.success_rate * 100).toFixed(1) }}%</div>
                    <div class="stat-card-label">整体成功率</div>
                </div>
            </div>

            <!-- 趋势图表 -->
            <div class="chart-card">
                <div class="chart-title">📈 工作流执行趋势（最近7天）</div>
                <div id="trendChart" class="chart-container"></div>
            </div>

            <!-- 状态分布图 -->
            <el-row :gutter="20" style="margin-bottom: 20px;">
                <el-col :span="12">
                    <div class="chart-card">
                        <div class="chart-title">📊 工作流状态分布</div>
                        <div id="statusChart" class="chart-container" style="height: 300px;"></div>
                    </div>
                </el-col>
                <el-col :span="12">
                    <div class="chart-card">
                        <div class="chart-title">⏱️ 执行时长统计</div>
                        <el-descriptions :column="1" border>
                            <el-descriptions-item label="平均时长">
                                {{ durationStats.average_duration }} 秒
                            </el-descriptions-item>
                            <el-descriptions-item label="最短时长">
                                {{ durationStats.min_duration }} 秒
                            </el-descriptions-item>
                            <el-descriptions-item label="最长时长">
                                {{ durationStats.max_duration }} 秒
                            </el-descriptions-item>
                            <el-descriptions-item label="统计样本">
                                {{ durationStats.total_count }} 个
                            </el-descriptions-item>
                        </el-descriptions>
                    </div>
                </el-col>
            </el-row>

            <!-- 最近实例列表 -->
            <div class="instance-list-card">
                <div class="chart-title" style="margin-bottom: 15px;">
                    🔄 最近的工作流实例
                    <el-button
                        type="primary"
                        size="small"
                        style="float: right;"
                        @click="loadRecentInstances">
                        刷新
                    </el-button>
                </div>

                <el-table
                    :data="recentInstances"
                    border
                    stripe
                    style="width: 100%">
                    <el-table-column prop="id" label="ID" width="80" align="center" />
                    <el-table-column prop="instance_name" label="实例名称" min-width="200" show-overflow-tooltip />
                    <el-table-column label="状态" width="120" align="center">
                        <template #default="{ row }">
                            <el-tag
                                :type="getStatusType(row.status)"
                                size="small">
                                {{ row.status }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="trigger_type" label="触发方式" width="100" align="center">
                        <template #default="{ row }">
                            <el-tag size="small" :type="row.trigger_type === 'manual' ? 'info' : 'warning'">
                                {{ row.trigger_type === 'manual' ? '手动' : '定时' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="执行耗时" width="120" align="center">
                        <template #default="{ row }">
                            <span v-if="row.duration">{{ row.duration }} 秒</span>
                            <span v-else style="color: #909399;">-</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="created_at" label="创建时间" width="180" align="center">
                        <template #default="{ row }">
                            {{ formatDate(row.created_at) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="100" align="center">
                        <template #default="{ row }">
                            <el-button
                                size="small"
                                type="primary"
                                link
                                @click="viewInstanceDetail(row.id)">
                                查看详情
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>

        <!-- 悬浮刷新按钮 -->
        <el-button
            type="primary"
            circle
            class="refresh-btn"
            :loading="refreshing"
            @click="refreshAll">
            <el-icon size="24"><Refresh /></el-icon>
        </el-button>
    </div>

    <script>
        const { createApp, ref, reactive, onMounted, onUnmounted } = Vue;
        const { ElMessage } = ElementPlus;

        createApp({
            setup() {
                const activeMenu = ref('monitoring');
                const refreshing = ref(false);
                const autoRefreshTimer = ref(null);

                // 统计数据
                const statistics = reactive({
                    running_workflows: 0,
                    today_success: 0,
                    today_failed: 0,
                    success_rate: 0,
                    trend: []
                });

                // 状态分布
                const statusDistribution = ref({});

                // 执行时长统计
                const durationStats = reactive({
                    average_duration: 0,
                    min_duration: 0,
                    max_duration: 0,
                    total_count: 0
                });

                // 最近实例
                const recentInstances = ref([]);

                // 图表实例
                let trendChart = null;
                let statusChart = null;

                // 加载统计数据
                const loadStatistics = async () => {
                    try {
                        const response = await axios.get('http://localhost:8000/api/monitoring/statistics');
                        Object.assign(statistics, response.data);

                        // 更新趋势图
                        updateTrendChart();
                    } catch (error) {
                        console.error('加载统计数据失败:', error);
                    }
                };

                // 加载状态分布
                const loadStatusDistribution = async () => {
                    try {
                        const response = await axios.get('http://localhost:8000/api/monitoring/status-distribution');
                        statusDistribution.value = response.data;

                        // 更新状态分布图
                        updateStatusChart();
                    } catch (error) {
                        console.error('加载状态分布失败:', error);
                    }
                };

                // 加载时长统计
                const loadDurationStats = async () => {
                    try {
                        const response = await axios.get('http://localhost:8000/api/monitoring/duration-statistics');
                        Object.assign(durationStats, response.data);
                    } catch (error) {
                        console.error('加载时长统计失败:', error);
                    }
                };

                // 加载最近实例
                const loadRecentInstances = async () => {
                    try {
                        const response = await axios.get('http://localhost:8000/api/monitoring/recent-instances?limit=20');
                        recentInstances.value = response.data.items;
                    } catch (error) {
                        console.error('加载最近实例失败:', error);
                    }
                };

                // 更新趋势图
                const updateTrendChart = () => {
                    if (!trendChart) return;

                    const dates = statistics.trend.map(item => item.date);
                    const successData = statistics.trend.map(item => item.success);
                    const failedData = statistics.trend.map(item => item.failed);

                    const option = {
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'shadow'
                            }
                        },
                        legend: {
                            data: ['成功', '失败']
                        },
                        grid: {
                            left: '3%',
                            right: '4%',
                            bottom: '3%',
                            containLabel: true
                        },
                        xAxis: {
                            type: 'category',
                            data: dates
                        },
                        yAxis: {
                            type: 'value'
                        },
                        series: [
                            {
                                name: '成功',
                                type: 'bar',
                                stack: 'total',
                                data: successData,
                                itemStyle: {
                                    color: '#67C23A'
                                }
                            },
                            {
                                name: '失败',
                                type: 'bar',
                                stack: 'total',
                                data: failedData,
                                itemStyle: {
                                    color: '#F56C6C'
                                }
                            }
                        ]
                    };

                    trendChart.setOption(option);
                };

                // 更新状态分布图
                const updateStatusChart = () => {
                    if (!statusChart) return;

                    const data = Object.entries(statusDistribution.value).map(([name, value]) => ({
                        name,
                        value
                    }));

                    const option = {
                        tooltip: {
                            trigger: 'item'
                        },
                        legend: {
                            orient: 'vertical',
                            left: 'left'
                        },
                        series: [
                            {
                                name: '工作流状态',
                                type: 'pie',
                                radius: '50%',
                                data: data,
                                emphasis: {
                                    itemStyle: {
                                        shadowBlur: 10,
                                        shadowOffsetX: 0,
                                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    }
                                }
                            }
                        ]
                    };

                    statusChart.setOption(option);
                };

                // 初始化图表
                const initCharts = () => {
                    trendChart = echarts.init(document.getElementById('trendChart'));
                    statusChart = echarts.init(document.getElementById('statusChart'));

                    // 响应式
                    window.addEventListener('resize', () => {
                        trendChart?.resize();
                        statusChart?.resize();
                    });
                };

                // 刷新所有数据
                const refreshAll = async () => {
                    refreshing.value = true;
                    try {
                        await Promise.all([
                            loadStatistics(),
                            loadStatusDistribution(),
                            loadDurationStats(),
                            loadRecentInstances()
                        ]);
                        ElMessage.success('刷新成功');
                    } catch (error) {
                        ElMessage.error('刷新失败');
                    } finally {
                        refreshing.value = false;
                    }
                };

                // 启动自动刷新
                const startAutoRefresh = () => {
                    autoRefreshTimer.value = setInterval(() => {
                        refreshAll();
                    }, 30000); // 每30秒刷新一次
                };

                // 停止自动刷新
                const stopAutoRefresh = () => {
                    if (autoRefreshTimer.value) {
                        clearInterval(autoRefreshTimer.value);
                        autoRefreshTimer.value = null;
                    }
                };

                // 获取状态类型
                const getStatusType = (status) => {
                    const statusMap = {
                        '已完成': 'success',
                        '运行中': 'primary',
                        '等待中': 'warning',
                        '失败': 'danger',
                        '已取消': 'info',
                        '暂停中': 'warning',
                        '已暂停': 'info'
                    };
                    return statusMap[status] || 'info';
                };

                // 查看实例详情
                const viewInstanceDetail = (instanceId) => {
                    // 跳转到工作流页面并查看详情
                    window.location.href = `workflow.html?instance=${instanceId}`;
                };

                // 格式化日期
                const formatDate = (dateStr) => {
                    if (!dateStr) return '';
                    const date = new Date(dateStr);
                    return date.toLocaleString('zh-CN');
                };

                // 菜单切换
                const handleMenuSelect = (index) => {
                    if (index === 'templates') {
                        window.location.href = 'index.html';
                    } else if (index === 'workflows') {
                        window.location.href = 'workflow.html';
                    } else if (index === 'workflow-templates') {
                        window.location.href = 'workflow_templates.html';
                    } else if (index === 'monitoring') {
                        // 当前页面
                    }
                };

                // 初始化
                onMounted(async () => {
                    initCharts();
                    await refreshAll();
                    startAutoRefresh();
                });

                // 清理
                onUnmounted(() => {
                    stopAutoRefresh();
                    trendChart?.dispose();
                    statusChart?.dispose();
                });

                return {
                    activeMenu,
                    refreshing,
                    statistics,
                    statusDistribution,
                    durationStats,
                    recentInstances,
                    loadRecentInstances,
                    refreshAll,
                    getStatusType,
                    viewInstanceDetail,
                    formatDate,
                    handleMenuSelect
                };
            }
        }).use(ElementPlus).mount('#app');
    </script>
</body>
</html>
